<?php

class Utils {
	// 根据id生成唯一订单号
	// sin函数在 0-∏/2 之间取值是唯一的，不过在 sin(1.4) 之后变化不明显
	// 所以取长度 9 的话，在 1400万 之后就要重新开始一个循环，用前缀作为区别
	// 这里是取的 9 位长度和 2 位前缀，可以保证14亿订单号不重复，如果不够，可延长到 10 位或者增加前缀的位数
	public static function build_order_no($id) {
		$pre = sprintf ( '%02d', $id / 14000000 ); // 每1400万的前缀
		$tempcode = sprintf ( '%09d', sin ( ($id % 14000000 + 1) / 10000000.0 ) * 123456789 ); // 这里乘以 123456789 一是一看就知道是9位长度，二则是产生的数字比较乱便于隐蔽
		$seq = '371482506'; // 这里定义 0-8 九个数字用于打乱得到的code
		$code = '';
		for($i = 0; $i < 9; $i ++)
			$code .= $tempcode [$seq [$i]];
		return $pre . $code;
	}
	
		
	/**
	 * 
	 * @author wanghch
	 * @email wanghch@mediav.com
	 * @date Apr 10, 2013
	 * @param array|string $data
	 * @param boolean $success
	 * @param string $msg
	 */
	public static function ajaxReturn($data='',$success = true,$msg = ''){
		header('Content-Type:application/json; charset=UTF-8');
		$res = array();
		if($success){
			$res['data'] = $data;
			$res['status'] = 0;
		}else{
			$res['status'] = 1;
			$res['msg'] = $msg;
		}
		echo CJSON::encode($res);
		Yii::app()->end();
	}
	
	
	
	public static function outputHiddenParams($params){
		foreach($params as $name=>$param){
			if(is_array($param) && !empty($param)){
				foreach ($param as $p){
					echo CHtml::hiddenField($name.'[]',$p);
				}
			}else if (is_string($param)){
				echo CHtml::hiddenField($name,$param);
			}
		}
	}
	
	public static function utc2LocalDatetime($utcDateTime){
		$timezone = "UTC"; 
		$d= DateTime::createFromFormat("Y-m-d\TH:i:se",$utcDateTime,new DateTimeZone($timezone));
		$d->setTimezone(new DateTimeZone('PRC'));
		return $d->format("Y-m-d H:i:s");
	}
	
	
	
	public static function  currency($from_Currency,$to_Currency,$amount) {        
		$amount = urlencode($amount);        
		$from_Currency = urlencode($from_Currency);        
		$to_Currency = urlencode($to_Currency);        
		$url = "http://www.google.com/ig/calculator?hl=en&q=$amount$from_Currency=?$to_Currency";        
		$ch = curl_init();        $timeout = 0;        
		curl_setopt ($ch, CURLOPT_URL, $url);        
		curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);        
		curl_setopt($ch,  CURLOPT_USERAGENT , "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");        
		curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);        
		$rawdata = curl_exec($ch);        
		curl_close($ch);        
		$data = explode('"', $rawdata);        
		$data = explode(' ', $data['3']);       
		$var = $data['0'];        
		return round($var,2);
	} 
		// echo currency("USD","EUR",100);
	public static function decodeBackboneData(){
		return CJSON::decode(file_get_contents("php://input"));
	}
	
	public static function getCurrencyUnit($currency){
		$return = '';
		switch($currency)
		{
			case 'CNY':
				$return = '￥';
				break;
			case 'USD':
				$return = '$';
				break;
		}
		return $return;
		
	}
}

?>